//
//  UIGridViewCell.m
//  GridViewUsingTableView
//
//  Created by Manoj Babu on 23/09/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "UIGridViewCell.h"

@interface UIGridViewCell()
-(void)releaseConnection;
-(void)startConnection;
@end

@implementation UIGridViewCell

@synthesize delegate;

-(id)init
{
    self = [super init];
    if(self)
    {
        _button = [[UIButton buttonWithType:UIButtonTypeCustom] retain];
        //_button.frame = CGRectMake(0, 0, frame.size.width, frame.size.height);
        [_button addTarget:self action:@selector(handleButtonTouchUpInside:) forControlEvents:UIControlEventTouchUpInside];
        _button.contentMode = UIViewContentModeScaleToFill;
        [self addSubview:_button];
        _url = nil;
        _imageQueue = dispatch_queue_create("com.test.gridviewcell", NULL);
    }
    return  self;
}

-(void)setCellFram:(CGRect)frame
{
    self.frame = frame;
    _button.frame = CGRectMake(0, 0, frame.size.width, frame.size.height);
}

-(void)loadCellAtIndex:(NSInteger)index withURL:(NSString *)url
{
    if(url != nil && index != _index && ![url isEqualToString:_url])
    {
       // _button.image = nil;
        [_button setImage:[UIImage imageNamed:@"thumbnailDefault"] forState:UIControlStateNormal];
        [self setNeedsDisplay];
        
        [_url release];
        _url = nil;
        _url = [url copy];
        _index = index;
        [self startConnection];
        /*dispatch_async(_imageQueue, ^{
           // NSString *currentURL = [_url copy];
            //NSInteger currentIndex = _index;
            NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:url]];//[NSURLConnection sendSynchronousRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:_url]] returningResponse:nil error:nil];//[NSData dataWithContentsOfURL:[NSURL URLWithString:url]];
            if(imageData != nil)// && currentIndex == _index && [currentURL isEqualToString:_url])
            {
                UIImage *image = [UIImage imageWithData:imageData]; 
                dispatch_async(dispatch_get_main_queue(), ^{
                    //[_button setImage:image forState:UIControlStateNormal];
                    _button.image = image;
                    //[self setNeedsDisplay];
                });
            }
            else
            {
                dispatch_async(dispatch_get_main_queue(), ^{
                    //[_button setImage:image forState:UIControlStateNormal];
                    _button.image = [UIImage imageNamed:@"Broken"];
                    [self setNeedsDisplay];
                });
            }
        });*/
    }
    else if(url == nil)
    {
        [self releaseConnection];
        //_button.image = [UIImage imageNamed:@"Broken"];
        [_button setImage:[UIImage imageNamed:@"Broken"] forState:UIControlStateNormal];
    }
    else
    {
        
    }
    //NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:url]];
    //UIImage *image = [UIImage imageWithData:imageData]; 
    //_button.image = [UIImage imageNamed:@"Broken"];
}

-(void)dealloc
{
    dispatch_release(_imageQueue);
    [_url release]; _url = nil;
    [_button release]; _button = nil;
    [super dealloc];
}

-(void)handleButtonTouchUpInside:(id)sender
{
    if([self.delegate respondsToSelector:@selector(didSelectCell:withIndex:)])
    {
        [self.delegate didSelectCell:self withIndex:_index];
    }
}

#pragma Private methods

-(void)releaseConnection
{
    [_connection release];
    _connection = nil;
    [imageData release];
    imageData = nil;
}

-(void)startConnection
{
    [self releaseConnection];
    _connection = [[UIGridViewCellConnection alloc] initWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:_url]] delegate:self];
    imageData = [[NSMutableData alloc] init];
    [_connection start];
}

#pragma NSURLConnection delegate methods

- (void)connection:(UIGridViewCellConnection *)connection didReceiveData:(NSData *)tdata
{
    if([connection.url isEqualToString:_url])
    {
        [imageData appendData:tdata];
    }
}

- (void)connection:(UIGridViewCellConnection *)connection didFailWithError:(NSError *)error
{
    if([connection.url isEqualToString:_url])
    {
        [_connection release];
        _connection = nil;
        [imageData release];
        imageData = nil;
        //_button.image = [UIImage imageNamed:@"Broken"];  
        [_button setImage:[UIImage imageNamed:@"Broken"] forState:UIControlStateNormal];
        [self setNeedsDisplay];
    }
}

- (void)connectionDidFinishLoading:(UIGridViewCellConnection *)connection
{
    if([connection.url isEqualToString:_url])
    {
        [_connection release];
        _connection = nil;
        //_button.image = [UIImage imageWithData:imageData];
        UIImage *image = nil;
        image = [UIImage imageWithData:imageData];
        if(image != nil)
            [_button setImage:image forState:UIControlStateNormal];
        else
            [_button setImage:[UIImage imageNamed:@"Broken"] forState:UIControlStateNormal];
        [self setNeedsDisplay];
        [imageData release];
        imageData = nil;
    }
}

@end

@implementation UIGridViewCellConnection

@synthesize url;

-(id)initWithRequest:(NSURLRequest *)request delegate:(id)delegate
{
    self = [super initWithRequest:request delegate:delegate];
    if(self)
    {
        NSURL *URL = [request URL];
        url = [[URL absoluteString] copy];
    }
    return self;
}

-(void)dealloc
{
    [url release];
    [super dealloc];
}

@end
